/*
 * Copyright 2023-2085 xujin <ceo@itgrail.com>
 *
 * Licensed under the Grail License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://itgrail.com/docs?id=3&catalogId=87
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.itgrail.pilot.infrastructure.adapters;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itgrail.grail.ddd.annotation.infrastructure.Adapter;
import com.itgrail.grail.shiro.util.MD5;
import com.itgrail.pilot.domain.user.contant.OkrConstants;
import com.itgrail.pilot.domain.user.entity.UserE;
import com.itgrail.pilot.domain.user.ports.UserPort;
import com.itgrail.pilot.infrastructure.converter.DingUserConverter;
import com.itgrail.pilot.infrastructure.tunnel.db.dao.UserMapper;
import com.itgrail.pilot.infrastructure.tunnel.db.dataobject.UserDO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;


@Adapter
public class UserAdapter implements UserPort {

    @Autowired
    private UserMapper mapper;

    @Autowired
    private DingUserConverter converter;

    @Override
    public Integer addUser(UserE userE) {
        UserDO userDO = converter.entityToData(userE);
        if(StringUtils.isEmpty(userDO.getPassword())){
            userDO.setPassword(MD5.md5("123456"));
        }
        userDO.setStatus(1);
        int insert = mapper.insert(userDO);
        userDO.setUserId(userDO.getId());
        mapper.updateById(userDO);
        return insert;
    }

    @Override
    public Integer updateUser(UserE userE) {
        UserDO userDO = converter.entityToData(userE);
        userDO.setUserId(userDO.getId());
        userDO.setStatus(1);
        return mapper.updateById(userDO);
    }

    @Override
    public String delete(UserE userE) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userE.getUserId());
        UserDO userDO = mapper.selectOne(queryWrapper);
        if (null != userDO) {
            userDO.setDeleted(OkrConstants.DELETED);
            mapper.updateById(userDO);
        }
        if (null != userDO && StringUtils.isNotEmpty(userDO.getAccount())) {
            return userDO.getAccount();
        }
        return "";
    }

}
